/*!
 * TidyBlog 2.0
 * Utility - v1.0.0 (2013-10-06T09:55:19+0800)
 * https://code.google.com/p/tidyblog/ | Released under MIT license
 */
define(function(require, exports, module) { 'use strict';

function formatDate(t, format) {
	var toTwoDigit = function(val) { return ("0" + val).slice(-2); },
		to12Hours = function(hours) { return hours > 12 ? hours - 12 : hours; };
		
	return format ? format.replace(/y+|m+|d+|h+|s+|H+|M+/g, function($0) {
		switch ($0) {
			case 'yyyy': return t.getFullYear();
			case 'yy': return toTwoDigit(t.getFullYear());
			case 'MM': return toTwoDigit(t.getMonth() + 1);
			case 'M': return t.getMonth() + 1;
			case 'dd': return toTwoDigit(t.getDate());
			case 'd': return t.getDate();
			case 'HH': return toTwoDigit(t.getHours());
			case 'H': return t.getHours();
			case 'hh': return toTwoDigit(to12Hours(t.getHours()));
			case 'h': return to12Hours( t.getHours() );
			case 'mm': return toTwoDigit(t.getMinutes());
			case 'm': return t.getMinutes();
			case 'ss': return toTwoDigit(t.getSeconds());
			case 's': return t.getSeconds();
			default: return $0;
		}
	}) : Date.prototype.toString.call(t);
}

function iFormatDate(date) {
	var now = new Date(), diff = now - date;
	if (diff < 60000) {
		return Math.max(1, parseInt(diff / 1000)) + "秒前";
	} else if (diff && diff < 3600000) {
		return Math.max(1, parseInt(diff / 60000)) + "分钟前";
	} else if (
		date.getFullYear() === now.getFullYear() &&
		date.getMonth() === now.getMonth() &&
		date.getDate()===now.getDate()
	) {
		return formatDate(date, "今天 HH:mm");
	} else {
		return formatDate(date, "yyyy年M月d日 H:mm");
	}
}

var re_cSharpDate = /^\/Date\((\d+)\)\/$/;
function parseCSharpDate(val) {
	return re_cSharpDate.test(val) ? new Date( parseInt(RegExp.$1) ) : null;
}

var htmlEntities = {
	'<' : '&lt;',
	'>' : '&gt;',
	'"' : '&quot;',
	"'" : '&#039;'
};
function htmlEncode(str) {
	return str ? str.replace(/[<>"']/g, function($0) {
		return htmlEntities[$0];
	}) : str;
}

var $ = require('dom/1.0.x/');
function onSubmitError(e) {
	alert( e.errorObjs.map(function(err) {
		return err.message;
	}).join('\r') );
	$(e.errorObjs[0].elements).focus();
}


return {
	iFormatDate: iFormatDate,
	parseCSharpDate: parseCSharpDate,
	htmlEncode: htmlEncode,
	onSubmitError: onSubmitError
}

});